package psn.kiko.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * WS连接的Text信息处理器
 */
@Slf4j
@Component
public class TextWsHandler extends TextWebSocketHandler{
	private static final CopyOnWriteArrayList<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
	
	//连接建立回调
	@Override
	public void afterConnectionEstablished(@Nonnull WebSocketSession session){
		sessions.add(session);
		log.debug("与{}建立连接",session.getRemoteAddress());
		logActiveSessionCount();
	}
	
	private void logActiveSessionCount(){
		log.info("活跃ws连接数：{}",(long) sessions.size());
	}
	
	//信息接收回调
	@Override
	protected void handleTextMessage(WebSocketSession session,TextMessage message) throws Exception{
		log.debug("收到来自{}的消息：{}",session.getRemoteAddress(),message.getPayload());
		for(WebSocketSession s: sessions){
			s.sendMessage(message);
		}
	}
	
	//连接关闭回调
	@Override
	public void afterConnectionClosed(@Nonnull WebSocketSession session,CloseStatus status){
		sessions.remove(session);
		log.debug("与{}断开连接，状态码：{}，原因：{}",session.getRemoteAddress(),status.getCode(),status.getReason());
		logActiveSessionCount();
	}
	
	//传输错误回调
	@Override
	public void handleTransportError(@Nonnull WebSocketSession session,Throwable e){
		sessions.remove(session);
		logActiveSessionCount();
		e.printStackTrace();
	}
	
	//自定义方法：广播信息
	public void broadCast(String msg) throws IOException{
		if(msg != null&&msg.length() > 0){
			TextMessage message = new TextMessage(msg.getBytes());
			for(WebSocketSession s: sessions){
				s.sendMessage(message);
			}
		}
	}
}